'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url client/pages/kh/index_userdata 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			todatStart
		} = data;
		let res = {
			code: 0,
			msg: "",
			todaySign: false,
			last_view: {},
			clickid: ""
		};
		res.userInfo = userInfo;
		// 业务逻辑开始-----------------------------------------------------------

		var nowtime = new Date().getTime()

		//====检查今日是否签到====
		const check_signCount = await db.collection('a_sign').where({
			user_id: userInfo._id,
			_add_time: _.gte(todatStart)
		}).count()
		if (check_signCount.total > 0) {
			res.todaySign = true
		}
		//====检查今日是否签到结束====

		//====获取用户的观看历史记录====
		const last_view = await db.collection('a_history').where({
			user_id: userInfo._id
		}).orderBy('_add_time', 'desc').limit(1).get()
		console.log("last_view", last_view);
		console.log("data", last_view.data[0]);
		res.last_view = last_view.data[0]
		//====获取用户的观看历史记录结束====
		//===改变用户的会员状态
		if (userInfo.plus_type == 0) {
			console.log("用户非会员");
		}
		//判断用户的会员到期没有，到期的话就把plus_type改为0
		let plus_type = userInfo.plus_type
		let plus_expire_time = userInfo.plus_expire_time
		if (plus_expire_time < nowtime && plus_type == 1) {
			console.log("用户会员已过期，改为普通用户");
			let updateVip = await db.collection('uni-id-users').doc(userInfo._id).update({
				plus_type: 0
			})
		}
		//===改变用户的会员状态结束
		// //如果用户信息里没有城市信息，则自动添加
		// if (!userInfo.city) {
		// 	//获取用户的地区信息
		// 	let userip = originalParam.context.CLIENTIP;
		// 	let ipurl = "http://whois.pconline.com.cn/ipJson.jsp?ip=" + userip + "&json=true";
		// 	let ip_result = await uniCloud.httpclient.request(ipurl, {
		// 		method: 'GET',
		// 		data: {},
		// 		contentType: 'json',
		// 		dataType: 'json'
		// 	})

		// 	let bind_address = await db.collection('uni-id-users').doc(userInfo._id).update({
		// 		province: ip_result.data.pro,
		// 		city: ip_result.data.city,
		// 	})
		// }

		//====修改用户的推广平台信息开始====
		//如果用户信息里存在clue_token，且不存在tg_pt，则更新用户推广平台为douyin
		if (userInfo.clue_token) {
			let update_tg_pt = await db.collection('uni-id-users').doc(uid).update({
				tg_pt: "douyin"
			})

			//======获取抖音回传参数======
			let percent = await db.collection('a_config').where({
				name: "RebackPercent",
				tfid: userInfo.tfid || 0
			}).get()
			let url = percent.data[0].douyin_url; //抖音广告资产化回传URL
			let token = percent.data[0].douyin_token; //抖音广告资产化回传token
			if (!url||!token) {
				res.t0 ="错误提示，请联系客服";
				res.t1 = "关闭弹窗";
				res.tips = "投放链接url和token没有填写"
			}
			if (percent.data[0] && url && token) {
				//回传用户激活数据

				let nonce = 8889;
				let times = vk.pubfn.toDecimal(new Date() / 1000, 0);
				const crypto = require('crypto');
				const sha1 = crypto.createHash('sha1');
				let strList = [token, times, nonce];
				strList.sort();
				let buffer = "";
				strList.forEach(str => {
					buffer += str;
				})
				let sign = sha1.update(buffer).digest('hex');
				let reback_url = url + "?timestamp=" + times + "&nonce=" + nonce + "&signature=" + sign;
				let jh_result = await uniCloud.httpclient.request(reback_url, {
					method: 'POST',
					data: {
						"clue_token": userInfo.clue_token,
						"open_id": userInfo.wx_openid['mp-weixin'],
						"event_type": "0", //参考：https://bytedance.feishu.cn/docx/doxcnmjDmhXc1Vial05xpvdu9ed
						"props": {
							"pay_amount": 0 //单位：分
						}
					},
					contentType: 'json',
					dataType: 'json'
				})
				console.log("激活回传结果=", jh_result);
				let update_reback1 = await db.collection('uni-id-users').doc(userInfo._id).update({
					reback: 1,
					rebacklog: "log:" + userInfo.clue_token
				})
				let add_log = await db.collection('jl_huichuanjilu').add({
					type: "激活回传",
					user_id: userInfo._id,
					tfid: userInfo.tfid || "",
					agent_id: userInfo.invite_code || 0,
					middleman_id: userInfo.middleman_id || 0,
					adid: userInfo.ad_id,
					result: jh_result
				})
			}
		}
		//====修改用户的推广平台信息结束====


		//判断用户是否有H5支付历史开始
		// let check_h5pay = await db.collection('a_h5pay').where({
		// 	pay_state: 1,
		// 	state: 0,
		// 	openid: userInfo.wx_openid['mp-weixin']
		// }).limit(1).get()
		// if (check_h5pay.data.length == 1) {
		// 	if (check_h5pay.data[0]._id.length > 10) {
		// 		//修改记录的状态值
		// 		let up_h5pay_state = await db.collection('a_h5pay').doc(check_h5pay.data[0]._id).update({
		// 			state: 1
		// 		})

		// 		let add_bean = check_h5pay.data[0].bean_number * 1;

		// 		//给对应的用户加金豆
		// 		let add_bean_log = await db.collection('uni-id-users').where({
		// 			['wx_openid.mp-weixin']: userInfo.wx_openid['mp-weixin']
		// 		}).update({
		// 			balance: _.inc(add_bean)
		// 		})

		// 		let add1 = await db.collection('a_jindou_detail').add({
		// 			user_id: userInfo._id,
		// 			nickname: userInfo.nickname,
		// 			change_num: add_bean,
		// 			change_reason: "H5支付充值" + add_bean + "金豆",
		// 			type: "income",
		// 			appid: userInfo.appid,
		// 			appname: userInfo.appname,
		// 			_add_time: nowtime
		// 		})
		// 	}
		// }
		//判断用户是否有H5支付历史结束

		//====判断用户是否已绑定广告平台信息====
		//用户已绑定广告平台的信息，则直接返回res
		if (userInfo.tg_pt || userInfo.clue_token) {
			return res;
		}


		//未绑定则继续执行：通过客户端IP查找jl_chudian里最后一条此IP的callback,且必须是一个小时内记录的，并通过此callback回传信息给巨量
		let ip = originalParam.context.CLIENTIP;
		let chudian_info = await db.collection('jl_chudian').where({
			ip: ip,
			time: _.gt(nowtime - 3600000)
		}).orderBy('time', 'desc').limit(1).get()
		let chudian_info1 = await db.collection('jl_chudian').where({
			wechat_openid: userInfo.wx_openid['mp-weixin'],
			time: _.gt(nowtime - 3600000)
		}).orderBy('time', 'desc').limit(1).get()
		//如果没找到该IP对应的触点信息,则直接返回res
		if (chudian_info.data.length != 1 && chudian_info1.data.length != 1) {
			return res;
		}

		//把ad_id和clickid带回客户端
		if (chudian_info.data.length != 0) {
			res.tg_pt = chudian_info.data[0].pt || "pt"; //平台
			res.ad_id = chudian_info.data[0].ad_id || "ad_id"; //广告主账号ID
			res.project_id = chudian_info.data[0].project_id || "project_id"; //巨量新版项目ID
			res.promotion_id = chudian_info.data[0].promotion_id || "promotion_id"; //巨量新版广告ID
			res.aid = chudian_info.data[0].aid || "aid"; //广告计划id
			res.cid = chudian_info.data[0].cid || "cid"; //广告创意id
			res.clickid = chudian_info.data[0].callback || "";
			//有clickid和ad_id时，绑定到用户信息里面
			let bind_adid = await db.collection('uni-id-users').doc(userInfo._id).update({
				tg_pt: res.tg_pt,
				ad_id: res.ad_id, //广告主账号ID
				project_id: res.project_id || "未匹配到新版项目ID", //新版项目ID
				aid: res.promotion_id || res.aid, //新版广告ID||广告计划id
				cid: res.cid, //广告创意id
				clickid: res.clickid,
				pageId: chudian_info.data[0].pageId //oppo广告专属-网页ID
			})
		} else {
			res.tg_pt = chudian_info1.data[0].pt || "pt"; //平台
			res.ad_id = chudian_info1.data[0].ad_id || "ad_id"; //广告主账号ID
			res.aid = chudian_info1.data[0].aid || "aid"; //广告计划id
			res.cid = chudian_info1.data[0].cid || "cid"; //广告创意id
			res.clickid = chudian_info1.data[0].callback || "";
			//有clickid和ad_id时，绑定到用户信息里面
			let bind_adid = await db.collection('uni-id-users').doc(userInfo._id).update({
				tg_pt: res.tg_pt,
				ad_id: res.ad_id, //广告主账号ID
				aid: res.aid, //广告计划id
				cid: res.cid, //广告创意id
				clickid: res.clickid,
			})
		}

		//如果找到了clickid且该用户激活信息未回传，就做一次激活回传。

		//快手：https://ad.kuaishou.com/
		if (res.tg_pt == "kuaishou" && userInfo.reback == 0) {
			//回传激活信息给快手
			let ksurl = "http://ad.partner.gifshow.com/track/activate?event_type=1&event_time=" + nowtime +
				"&callback=" + res.clickid
			let kshuichuan_result = await uniCloud.httpclient.request(ksurl, {
				method: 'GET',
				data: {},
				contentType: 'json',
				dataType: 'json'
			})
			let ks_update_reback = await db.collection('uni-id-users').doc(userInfo._id).update({
				reback: 1
			})
		}

		//巨量引擎：https://www.oceanengine.com/
		if (res.tg_pt == "douyin" && userInfo.reback == 0) {
			// 回传关键页面触发事件给巨量，参考文档：http://event-manager.oceanengine.com/docs/8650/h5_api_docs/
			//转化回传事件全集：https://event-manager.oceanengine.com/docs/8650/all_events/
			let jlurl = "https://analytics.oceanengine.com/api/v2/conversion"
			let tthuichuan_result = await uniCloud.httpclient.request(jlurl, {
				method: 'POST',
				data: {
					"event_type": "active",
					"context": {
						"ad": {
							"callback": res.clickid, //callback，填写clickid
						}
					},
					"timestamp": nowtime
				},
				contentType: 'json', // 指定以application/json发送data内的数据
				dataType: 'json' // 指定返回值为json格式，自动进行parse
			})
			let dy_update_reback = await db.collection('uni-id-users').doc(userInfo._id).update({
				reback: 1
			})
		}

		//UC超级汇川：e.uc.cn
		if (res.tg_pt == "uc" && userInfo.reback == 0) {
			console.log("执行用户登录时间给UC回传");
			// 回传支付事件给UC广告平台https://www.yuque.com/chaojihuichuan/hhcp03/li07c0?singleDoc=
			let nows = new Date().getTime()
			let purchase_amount = 1;
			let ucurl = res.clickid + "&type=65&money=" + purchase_amount + "&event_time=" + nows
			let uchuichuan_result = await uniCloud.httpclient.request(ucurl, {
				method: 'GET',
				data: {},
				contentType: 'json',
				dataType: 'json'
			})
			//UC返回成功形式为{"status":0}
			let uc_update_reback = await db.collection('uni-id-users').doc(userInfo._id).update({
				reback: 1
			})
		}

		//腾讯广点通：e.qq.com
		if (res.tg_pt == "tengxun" && userInfo.reback == 0) {
			// let nows = new Date().getTime()
			// let ts_10 = Math.round(new Date().getTime() / 1000).toString();
			// // 回传支付事件给腾讯https://docs.qq.com/pdf/DQm1PUWRHZVdudkRG?
			// //回传事件类型：https://developers.e.qq.com/docs/guide/conversion/new_version/Web_api
			// let tengxunurl =
			// 	"http://tracking.e.qq.com/conv/web?clickid=" + res.clickid + "&action_time=" + ts_10 +
			// 	"&action_type=VIEW_CONTENT&link=tracking.e.qq.com";
			// let tengxunhuichuan_result = await uniCloud.httpclient.request(tengxunurl, {
			// 	method: 'GET',
			// 	data: {},
			// 	contentType: 'json',
			// 	dataType: 'json'
			// })
			// let request_id = vk.pubfn.getUniCloudRequestId();
			// let look_log = await db.collection('vk-test').add({
			// 	tips: "查看腾讯注册回传",
			// 	request_id: request_id,
			// 	_add_time: _add_time,
			// 	_add_time_str: _add_time_str
			// })
			// console.log("执行腾讯广告回传");
			//获取用户的callback 
			let chudian = await vk.baseDao.findByWhereJson({
				dbName: "jl_chudian",
				whereJson: {
					callback: res.clickid,
				}
			});
			console.log("351行=》", chudian);
			let callback_url = chudian.callback_url
			//获取用户的openid 
			let wechat_openid = chudian.wechat_openid
			// //获取短剧名称
			// let product_name = orderinfo.tv_name
			// //获取短剧的id 
			// let tv = await vk.baseDao.findByWhereJson({
			// 	dbName: "a_tv",
			// 	whereJson: {
			// 		tv_name: product_name,
			// 	}
			// });
			// console.log("364行=》", tv);
			// let product_id = tv._id
			// 回传注册事件给腾讯广告平台
			let nows = new Date().getTime()
			let ts_10 = Math.round(new Date().getTime() / 1000).toString();
			// 回传支付事件给腾讯https://docs.qq.com/pdf/DQm1PUWRHZVdudkRG?
			//回传事件类型：https://developers.e.qq.com/docs/guide/conversion/new_version/Web_api
			// let tengxunurl =
			// 	"http://tracking.e.qq.com/conv/web?clickid=" + clickid + "&action_time=" + ts_10 +
			// 	"&action_type=PURCHASE&value=" + total_fee + "&link=tracking.e.qq.com";
			let tengxunurl = callback_url
			let tengxunhuichuan_result = await uniCloud.httpclient.request(tengxunurl, {
				"headers": {
					"Content-Type": 'application/json',
					"cache-control": 'no-cache'
				},
				method: 'POST',
				data: {
					"actions": [{
						"outer_action_id": "", // （选填）客户唯一行为id
						"action_time": ts_10,
						"user_id": { // user_id， 对应小程序的openid
							"wechat_openid": wechat_openid, // 必填
							"wechat_app_id": "wxdad3b6f00b92a6c2", // 微信类上报必填，且必须通过授权。授权请参考微信数据接入
						},
						"trace": {
							"click_id": res.clickid // 必填 click_id
						},
						"action_type": "REGISTER", // 必填 行为类型，下单为COMPLETE_ORDER、付费为PURCHASE、REGISTER为注册

					}]
				},
				// contentType: 'json',
				// dataType: 'json'
			})
			let tx_update_reback = await db.collection('uni-id-users').doc(userInfo._id).update({
				reback: 1,
				tengxunhuichuan_result: tengxunhuichuan_result
			})
		}


		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}